package pkg.networking;
import java.awt.Event;
import java.awt.Graphics2D;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import pkg.*;
import pkg.commands.*;
public class NetworkComponent extends GameComponent implements INetworkCallback {
	
	private EntityManager entitys;
	private RemoteDistributor distributor;
	private ClientConnection client;
	private BombServer server;
	private boolean isHost;
	private String name;
	private NetworkedPlayer player;//player we are networking over network
	
	public NetworkComponent(String name,boolean isHost)
	{
		this.isHost = isHost;
		this.name = name;
		ConsoleHandler console = new ConsoleHandler();
		console.setLevel(Level.ALL);
		console.setFormatter(new LogFormat());
		Logger.getLogger("Bomb").addHandler(console);
		Logger.getLogger("Bomb").setUseParentHandlers(false);
		Logger.getLogger("Bomb").setLevel(Level.INFO);
		Logger.getLogger("Bomb").setFilter(null);
	
	}
	
	public NetworkComponent(boolean isHost)
	{
		this("Null Name",isHost);
	}
	
	protected void initialize()
	{
	    entitys = findComponent(EntityManager.class);
	    entitys.setFactory(new NetworkEntityFactory());
	    player = (NetworkedPlayer)entitys.createEntity("player");
		ICommandExecutor exec = new PlayerExecutor(entitys);
		ICommandExecutor sysExec = new SysExecutor(entitys);

		start(1024);
		connect("141.209.197.89", 1024);
		
		entitys.getDistributor().register(exec);
		entitys.getDistributor().register(sysExec);
		entitys.getDistributor().register(distributor);
	}
	
	private void connect(String address, int port)
	{
		client = new ClientConnection();
		client.setName(name);
		client.registerListener(this);
		distributor = new RemoteDistributor(client);
		client.connect(address, port);
		entitys.getDistributor().register(distributor);
	}
	
	private void start(int port)
	{
		if(isHost)
		{
			server = new BombServer();
			server.start(port);
		}
	}
	
	public NetworkedPlayer getPlayer()
	{
		return player;
	}
	

	@Override
	public void render(Graphics2D g) {
		
	}

	@Override
	public void update(float dt) {
	}

	@Override
	public void newtworkEvent(CallbackEvent evnt, Object obj) {		
		if(evnt == CallbackEvent.SessionJoined)
			player.setUserID(client.getUserId());
		else if(evnt == CallbackEvent.SyncPosition)
		{
			RemoteCommand cmd = new RemoteCommand(PlayerCmd.synchPosition(client.getUserId(), player.getPosition()),client.getUserId());
			client.sendMessage(cmd);
		}

	}

}
